package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.constant.OrderStatusEnum;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.utils.R;
import com.atguigu.entity.to.OrderTo;
import com.atguigu.entity.to.SeckillOrderTO;
import com.atguigu.entity.vo.MemberResponseVo;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.entity.to.OrderCreateTo;
import com.atguigu.gulimall.order.entity.vo.*;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo = new OrderConfirmVo();

        //从拦截器中获取登录用户
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //获取原来请求中的RequestAttributes，在异步线程中重新set一次，以达到异步线程共享数据问题
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1。远程查询所有的收货地址
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //在异步线程中重新set一次，以达到异步线程共享数据问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R r = memberFeignService.getAddress(memberResponseVo.getId());
            if (r.getCode() == 0) {
                List<MemberAddressVo> address = r.getData(new TypeReference<List<MemberAddressVo>>() {
                });

                confirmVo.setMemberAddressVos(address);
            }
        }, executor);


        //2.远程查询购物车所有选中的购物项目
        CompletableFuture<Void> itemFuture = CompletableFuture.runAsync(() -> {
            //在异步线程中重新set一次，以达到异步线程共享数据问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> cartItems = cartFeignService.getRurrentUserCartItems();
            confirmVo.setItemVos(cartItems);

            //feign在远程调用之前要创建一个新的请求，会调用很多拦截器，新的请求会丢失之前的请求头信息
            //RequestInterceptor interceptor
            //给feign添加自己的请求拦截器
            //继续查询库存信息
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> itemVos = confirmVo.getItemVos();
            List<Long> skuIds = itemVos.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());

            //继续查询库存信息
            R r = wmsFeignService.hasstoke(skuIds);
            if (r.getCode() == 0){
                List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
                });

                if (data != null){
                    Map<Long, Boolean> booleanMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::isHasStoke));
                    confirmVo.setStocks(booleanMap);
                }
            }

        }, executor);

        //3.查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4.查询其他优惠券，发票信息....

        //5.等待上面的异步处理完成
        CompletableFuture.allOf(addressFuture,itemFuture).get();

        //6.其他数据OrderConfirmVo里自动计算

        //7.orderToken防重令牌
        //服务器保存一份，给客户端发送一份，后期用来比较
        String toker = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(toker);
        //30分钟有效期
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResponseVo.getId(),toker,30, TimeUnit.MINUTES);

        return confirmVo;
    }

    @Transactional(timeout = 30)
    public void a(){
        //a 调用自己bc方法，这种模式下，b c做任何设置都是没用的，都是和a共用一个事物
        //因为事物使用代理对象来控制的，绕过来代理对象，会有本地事物失效问题
        //解决办法见启动类
//        b();//a事物
//        c();//新事物
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();
        orderService.c();

//        bService.b();//a事物，回滚
//        cService.c();//新事物,不回滚
//        int i = 10 / 0;//异常 a 和 b回滚，c不回滚
    }

    //REQUIRED 标示b和a共用同一个事物
    @Transactional(propagation = Propagation.REQUIRED,timeout = 2)
    public void b(){
        //7s 不超时， 和a事物共用一个为30秒，b的2秒没效果，要起效果使用REQUIRES_NEW
    }

    //REQUIRES_NEW 标示c和a不共用同一个事物，自己创建一个新事物
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c(){

    }

    /**
     * 隔离级别
     * READ_UNCOMMITTED 可读未提交的，有脏读现象，别人回滚了
     *READ_COMMITTED 读已提交的
     * REPEATABLE_READ 可重复读 默认
     *
     * 传播行为
     * propagation
     *
     * @GlobalTransactional 高并发下不适合使用，对于后台配置低并发情况适合
     * 高并发下可以使用
     */
//    @GlobalTransactional //全局事物
    @Transactional
//    @Transactional(isolation = Isolation.REPEATABLE_READ)
    //本地事物，在分布式系统里，只能控制自己回滚，控制不了其他服务的回滚
    //分布式事物：最大原因：网络问题+分布式机器
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        //下单：去创建订单 验令牌 验价格 锁库存。。。。。
        //从拦截器中获取登录用户信息
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);

        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        //使用ThreadLocal在同一个线程中传递数据
        confirmVoThreadLocal.set(vo);
        //获取验证令牌
        //[令牌获取，对比和删除必须是一个原子性操作]
        //脚本返回的都是0和1 0总是代表失败
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
//        String redisToken = (String) redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
//        if (redisToken != null && redisToken.equals(orderToken)){
//            //令牌验证通过
//            //令牌验证通过后要将其删除，否则后面重复提交的还会验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
//        }else {
//            //令牌验证不通过
//        }
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()),
                orderToken);
        if (result == 0){
            //令牌验证不通过
            responseVo.setCode(1);
            return responseVo;
        }
        //令牌验证通过
        //创建订单
        OrderCreateTo order = createOrder();
        //验价
        BigDecimal payAmount = order.getOrderEntity().getPayAmount();//订单价格
        BigDecimal payPrice = vo.getPayPrice();//页面提交的价格
        //价格在0.01的误差之内算比较成功
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) >= 0.01){
            responseVo.setCode(2);
            return responseVo;
        }
        //TODO 3.验价成功
        //保存订单
        saveOrder(order);

        //库存锁定.整个过程在同一个事物中，只要有异常，回滚订单数据
        //订单号 订单项目 锁几件 （skuId，skuName num）
        WareSkuLockVo lockVo = new WareSkuLockVo();
        lockVo.setOrderSn(order.getOrderEntity().getOrderSn());

        List<OrderItemEntity> itemEntities = order.getItemEntities();
        List<OrderItemVo> collect = itemEntities.stream().map(item -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(item.getSkuId());
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setTitle(item.getSkuName());

            return orderItemVo;
        }).collect(Collectors.toList());
        lockVo.setLocks(collect);

        //TODO 4.远程锁库存，很重要
        //问题一：如果锁库存出现假异常，比如服务超时，库存扣成功了，订单却回滚了
        //问题二：如果锁库存成功了，扣积分出现了异常，订单回滚了，但执行成功的远程但库存不会回滚
        //为了保证高并发，订单回滚了，库存自己回滚，出现异常可以发消息给库存服务
        //库存本身也可以使用自解锁
        R r = wmsFeignService.orderLockStock(lockVo);
        if (r.getCode() == 0){
            //锁定成功
            responseVo.setOrderEntity(order.getOrderEntity());

            //TODO 5远程构建积分
            //问题二：如果锁库存成功了，扣积分出现了异常，订单回滚了，但执行成功的远程但库存不会回滚
//            int i = 10 / 0;
            //TODO 订单创建成功发送消息给MQ
            rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrderEntity());
            return responseVo;
        }else {
            //锁定失败
            throw new NoStockException();
//            responseVo.setCode(3);
//            return responseVo;
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关闭订单
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode() == orderEntity.getStatus()){
            //关单 只更新状态
            OrderEntity upOrder = new OrderEntity();
            upOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            upOrder.setId(orderEntity.getId());

            this.updateById(upOrder);

            //主动发送一次消息，告诉库存解锁库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderTo,orderEntity);
            try {
                //TODO 保存消息一定会发送出去，方式消息丢失
                /**
                 * 消息发送出去，由于网络原因没有抵达服务器
                 * 解决：做好try catch，将没发送成功的消息进行重试发送
                 *  每个消息做好日志记录(在数据库保存好每一个消息的详细信息)
                 *
                 *  消息抵达Broker ，Broker要将消息写入磁盘持久化才算成功。此时
                 *  Borker尚未持久化完成，服务器死机了，消息丢失
                 *  解决：开启消息确认机制，确认成功的消息，修改数据库消息状态
                 *
                 *  自动ACK状态下，消费者收到消息，但还没来得及处理就司机
                 *  解决：开启消息手动确认机制，只有消费成功了才ack
                 */
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.order",orderTo);
            } catch (AmqpException e) {

            }
        }
    }

    /**
     * 获取当前订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);

        //将金额取两位小数，多少的部分向上取 如0.01001->0.02
        String amount = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString();

        payVo.setBody(entity.getSkuAttrsVals());//订单的备注 使用商品的销售属性来做备注
        payVo.setOut_trade_no(orderSn);//订单号
        payVo.setSubject(entity.getSkuName());//订单标题 使用第一个订单项的名字作为这个订单的标题
        payVo.setTotal_amount(amount);//订单金额

        return payVo;
    }


    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberResponseVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> collect = page.getRecords().stream().map(order -> {

            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntitys(order_sn);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(collect);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {

        //保存交易流水，后期对账
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());

        paymentInfoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(paymentInfoEntity);

        //修改订单的状态信息
        String trade_status = vo.getTrade_status();
        //支付成功
        if (trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED")){
            String orderSn = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTO entity) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(entity.getOrderSn());
        orderEntity.setMemberId(entity.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //应付价格
        BigDecimal multiply = entity.getSeckillPrice().multiply(new BigDecimal("" + entity.getNum()));
        orderEntity.setPromotionAmount(multiply);
        //........

        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(entity.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(entity.getNum());
        //.......

        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrderEntity();
        this.save(orderEntity);

        //保存订单项
        List<OrderItemEntity> itemEntities = order.getItemEntities();
        orderItemService.saveBatch(itemEntities);
    }

    /**
     * 创建一个订单
     * @return
     */
    private OrderCreateTo createOrder(){

        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //1。创建订单号
        String orderSn = IdWorker.getTimeId();

        //2。构建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        orderCreateTo.setOrderEntity(orderEntity);

        //3.获取订单项
        List<OrderItemEntity> orderItemEntities = buildAllOrderItem(orderSn);
        orderCreateTo.setItemEntities(orderItemEntities);

        //4.验价 计算价格相关
        computePrice(orderEntity,orderItemEntities);

        orderCreateTo.setOrderEntity(orderEntity);
        orderCreateTo.setItemEntities(orderItemEntities);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //订单价格相关
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        BigDecimal giftIntegration = new BigDecimal("0.0");
        BigDecimal giftGrowth = new BigDecimal("0.0");

        //计算订单总额
        for (OrderItemEntity entity : orderItemEntities) {
            //计算各种优惠 优惠 积分 打折
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());

            //订单总额
            total = total.add(entity.getRealAmount());

            //这个订单获得的总积分和总成长值
            giftIntegration = giftIntegration.add(new BigDecimal(entity.getGiftIntegration().toString()));
            giftGrowth = giftGrowth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //订单总额
        orderEntity.setTotalAmount(total);
        //应付总额 需要加上运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        //各种优惠总额
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分和成长值
        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());

        orderEntity.setDeleteStatus(0);//未删除
    }


    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);

        //订单的会员id
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(memberResponseVo.getId());

        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        //2。填充收货地址
        R r = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        if (r.getCode() == 0){
            //运费地址相关信息
            FareVo data = r.getData(new TypeReference<FareVo>() {
            });

            //运费
            BigDecimal fare = data.getFare();
            //收货人地址信息
            orderEntity.setFreightAmount(fare);
            orderEntity.setReceiverCity(data.getAddressVo().getCity());
            orderEntity.setReceiverDetailAddress(data.getAddressVo().getDetailAddress());
            //收货人信息
            orderEntity.setReceiverName(data.getAddressVo().getName());
            orderEntity.setReceiverPhone(data.getAddressVo().getPhone());
            orderEntity.setReceiverPostCode(data.getAddressVo().getPostCode());
            orderEntity.setReceiverProvince(data.getAddressVo().getProvince());
            orderEntity.setReceiverRegion(data.getAddressVo().getRegion());
        }

        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    //构建所有订单项目
    private List<OrderItemEntity> buildAllOrderItem(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> cartItems = cartFeignService.getRurrentUserCartItems();
        if (cartItems != null && cartItems.size() > 0){
            List<OrderItemEntity> orderItems = cartItems.stream().map(cartItem -> {
                OrderItemEntity orderItem = buildOrderItem(cartItem);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());

            return orderItems;
        }
        return null;
    }

    //构建一个订单项目
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem){
        OrderItemEntity orderItem = new OrderItemEntity();
        //1.订单信息：订单号
        //2.商品spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoByskuId(skuId);
        if (r.getCode() == 0){
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
            });
            orderItem.setSpuId(data.getId());
            orderItem.setSpuName(data.getSpuName());
            orderItem.setSpuBrand(data.getBrandId().toString());
            orderItem.setCategoryId(data.getCatalogId());
        }

        //3.商品sku信息
        orderItem.setSkuId(cartItem.getSkuId());
        orderItem.setSkuName(cartItem.getTitle());
        orderItem.setSkuPic(cartItem.getImage());
        orderItem.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItem.setSkuAttrsVals(skuAttr);
        orderItem.setSkuQuantity(cartItem.getCount());

        //4。优惠信息【不做】
        //5。积分信息
        orderItem.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItem.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6.价格信息
        orderItem.setPromotionAmount(new BigDecimal("0.0"));
        orderItem.setCouponAmount(new BigDecimal("0.0"));
        orderItem.setIntegrationAmount(new BigDecimal("0.0"));
        //当前订单项的实际金额
        BigDecimal orign = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        //订单价格减去各种优惠后当价格为实际金额
        orign.subtract(orderItem.getPromotionAmount()).subtract(orderItem.getCouponAmount()).subtract(orderItem.getIntegrationAmount());
        orderItem.setRealAmount(orign);
        
        return orderItem;
    }

}